package com.thinkit.security.config;
import com.thinkit.utils.properties.PermitAllUrlProperties;
import com.thinkit.utils.utils.Checker;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

public class AuthcPathRequestMatcher implements RequestMatcher {

    private PermitAllUrlProperties permitAllUrlProperties;

    private String application;

    public AuthcPathRequestMatcher(PermitAllUrlProperties urlProperties, String application) {
        this.application =application;
        this.permitAllUrlProperties = urlProperties;
        init();
    }

	private RequestMatcher authcMatchers;

	public void init() {
	    List<String> authcToSkip = permitAllUrlProperties.authcs(application);
	    if(Checker.BeNotEmpty(authcToSkip)){
            List<RequestMatcher> m = authcToSkip.stream().map(path -> new AntPathRequestMatcher(path)).collect(Collectors.toList());
            authcMatchers = new OrRequestMatcher(m);
        }
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        return authcMatchers.matches(request);
    }
}
